//实现二分查找

public class twoParititonSearch {
    public static void main(String[] args) {
        int[] nums = new int[]{1,2,3,4,7,9};
        int res1 = func1(nums,7);
        int res2 = func2(nums,9,0,nums.length-1);
        System.out.println(res1);
        System.out.println(res2);
    }

    //迭代循环实现
    public static int func1(int[] arr, int target){
        int left = 0;
        int right = arr.length-1;
        int mid = 0;
        while(left <= right){
            mid = (left + right) / 2;
            if(arr[mid] == target){
                return mid;
            }
            if(arr[mid]< target){
                left = mid+1;
            }else if(arr[mid] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }

    //递归实现
    //注意return
    public static int func2(int[] arr,int target, int left, int right){
        if(right < left){
            return -1;
        }
        int mid = (left + right) / 2;
        if(arr[mid] < target){
            return func2(arr,target,mid+1,right);
        }else if (arr[mid] > target){
            return func2(arr,target,left,mid-1);
        }else{
            return mid;
        }
    }
}
